package cn.pku.sirx.snad.acls.web;

import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import cn.pku.sirx.snad.ad.Constants;
import cn.pku.sirx.snad.ad.domain.IAdClickLogFacade;
import cn.pku.sirx.snad.ad.model.UserContext;
import cn.pku.sirx.snad.ad.model.entity.AdClickLog;
import cn.pku.sirx.snad.ad.util.UserContextStringUtils;

/**
 * @author WangXiao
 */
public class AdClickLogController extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		/*
		 * persist click log
		 */
		AdClickLog adClickLog = getAdClickLog(request);
		if (adClickLog != null) {
			adClickLogFacade.insert(adClickLog);
		} else {
			LOG
					.info("failed to get ad click log: "
							+ request.getParameterMap());
		}
		/*
		 * redirect
		 */
		String landingPageUrl = ServletRequestUtils.getStringParameter(request,
				Constants.WEB_P_LANDING_PAGE_URL);
		if (landingPageUrl != null) {
			response.sendRedirect(landingPageUrl);
		}
		return null;
	}

	private AdClickLog getAdClickLog(HttpServletRequest request)
			throws ServletException {
		Long adId = ServletRequestUtils.getLongParameter(request,
				Constants.WEB_P_AD_ID);
		if (adId != null) {
			UserContext userContext = UserContextStringUtils
					.toUserContext(request);
			String userId = userContext.getUserId();
			String userIp = request.getRemoteAddr();
			return new AdClickLog(userId, adId, new Date(), userIp);
		}
		return null;
	}

	private static final Log LOG = LogFactory
			.getLog(AdClickLogController.class);

	private IAdClickLogFacade adClickLogFacade;

	public void setAdClickLogFacade(IAdClickLogFacade adClickLogFacade) {
		this.adClickLogFacade = adClickLogFacade;
	}

}
